package com.dawn.sinaoption.serviceimpl;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.WeiboException;

import com.dawn.idolmanage.bean.IdolInfoBean;
import com.dawn.idolmanage.dao.IdolManageDao;
import com.dawn.sinaoption.service.SinaService;
import com.dawn.trademanage.bean.TradeInfoBean;
import com.dawn.trademanage.service.TradeManageService;
import com.dawn.usermanage.bean.UserBean;
import com.dawn.utils.exceptions.DaoAccessException;

@Service
public class SinaServiceImpl implements SinaService {

    private static Logger logger = Logger.getLogger(SinaServiceImpl.class);

    private static final String ERRORINFO1 = "不可关注本人";
    private static final String ERRORINFO2 = "您已经关注过此人";
    private static final String ERRORINFO3 = "链接微博失败";
    private static final String ERRORINFO4 = "数据错误";

    @Autowired
    private IdolManageDao idolManageDao;
    @Autowired
    private TradeManageService tradeManageService;

    @Override
    public String followSinaer(Long userId, String sinaId, int tradeId, String accessToken, String accessTokenSecret) {
        int followPrice = 0;
        try {
            TradeInfoBean tradeInfo = tradeManageService.findTradeById(tradeId);
            if(tradeInfo == null)
                return ERRORINFO4;
            String idolId = tradeInfo.getTuUserinfo().getTwSinainfo().getSinaId();
            followPrice = tradeInfo.getUnitPrice();
            if (sinaId.equals(idolId))
                return ERRORINFO1;
            if (!idolManageDao.findUser(userId, idolId).isEmpty())
                return ERRORINFO2;
            Weibo weibo = new Weibo();
            weibo.setToken(accessToken, accessTokenSecret);
            User user = weibo.createFriendship(idolId);
            IdolInfoBean idolInfo = new IdolInfoBean();
            idolInfo.setFollowTime(new Date());
            idolInfo.setIdolID(idolId);
            idolInfo.setIdolName(user.getScreenName());
            idolInfo.setSinaId(sinaId);
            idolInfo.setTradeId(tradeId);
            idolInfo.setFollowPrice(followPrice);
            UserBean userBean = new UserBean();
            userBean.setUserId(userId);
            idolInfo.setTuUserinfo(userBean);
            idolManageDao.addIdolInfo(idolInfo);
        } catch (WeiboException e) {
            logger.error("Init sina weibo failed.");
            e.printStackTrace();
            return ERRORINFO3;
        } catch (Exception e) {
            logger.error("Data access error.");
            throw new DaoAccessException();
        }
        return String.valueOf(followPrice);
    }

}
